package com.cenxi.utils;

import com.cenxi.utils.constants.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class HttpUtil {

    /**
     * 获取客户端IP
     *
     * @param request 请求对象
     * @return IP地址
     */
    public static String getRemoteAddress(HttpServletRequest request) {
        if (request == null) {
            return "unknown";
        }
        String ip = request.getHeader(Constants.REAL_IP);

        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : getMultistageReverseProxyIp(ip);
    }

    /**
     * 从多级反向代理中获得第一个非unknown IP地址
     *
     * @param ip 获得的IP地址
     * @return 第一个非unknown IP地址
     */
    public static String getMultistageReverseProxyIp(String ip) {
        // 多级反向代理检测
        if (ip != null && ip.indexOf(",") > 0) {
            final String[] ips = ip.trim().split(",");
            for (String subIp : ips) {
                if (false == isUnknown(subIp)) {
                    ip = subIp;
                    break;
                }
            }
        }
        return ip;
    }

    /**
     * 检测给定字符串是否为未知，多用于检测HTTP请求相关
     *
     * @param checkString 被检测的字符串
     * @return 是否未知
     */
    public static boolean isUnknown(String checkString) {
        return StringUtils.isBlank(checkString) || "unknown".equalsIgnoreCase(checkString);
    }

    /**
     * 通过请求对象，获取访问路径
     *
     * @param request
     * @param includeContextPath
     * @return
     */
    private static String getRequestURI(HttpServletRequest request, boolean includeContextPath) {
        String requestURI = request.getRequestURI();
        if (includeContextPath) {
            return requestURI;
        } else {
            String contextPath = request.getContextPath();
            return requestURI.replace(contextPath, "");
        }
    }

    public static String getRequestURI(HttpServletRequest request) {
        return getRequestURI(request, false);
    }

    public static String getFullRequestURI(HttpServletRequest request) {
        return getRequestURI(request, true);
    }

    public static void main(String[] args) {
        List<Long> r = new ArrayList<>();

        List<Long> r1 = new ArrayList<>();
        r.addAll( r1);
        r = r.stream().distinct().collect(Collectors.toList());
        r.forEach(System.out::println);
    }
}
